package com.alei.redis.redisdemo.controller;

import com.alei.redis.redisdemo.bean.SysMenu;
import com.alei.redis.redisdemo.mapper.SysMenuMapper;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ShiLei
 * @version v1.0
 * @date 2020-09-04 10:17
 */
@RestController
@RequestMapping("api/sysmenu/")
@Slf4j
public class SysMenuController {

    private static final String DICT_KEY = "dict";
    public static Boolean FLAG = true;
    @Resource
    private JedisPool jedisPool;
    @Resource
    private SysMenuMapper sysMenuMapper;

    @PostMapping("/findInfo")
    public List<SysMenu> findInfo(@RequestBody @Validated SysMenu sysMenu) {
        log.info("查询菜单配置开始,参数:{}", sysMenu);
        if (null == sysMenu.getType()) {
            throw new RuntimeException("服务器异常~");
        }
        if (FLAG) {
            try (Jedis jedis = jedisPool.getResource()) {
                String result = jedis.hget(DICT_KEY, sysMenu.getType());
                if (!StringUtils.isEmpty(result)) {
                    return JSON.parseArray(result, SysMenu.class);
                }
                List<SysMenu> list = sysMenuMapper.findByType(sysMenu.getType());
                if (CollectionUtils.isEmpty(list)) {
                    jedis.hset(DICT_KEY, sysMenu.getType(), null);
                    return new ArrayList<>();
                }
                jedis.hset(DICT_KEY, sysMenu.getType(), JSON.toJSONString(list));
                return list;
            } catch (JedisConnectionException e) {
                e.printStackTrace();
                FLAG = false;
                //再开一个定时任务线程 测试 redis 状态
            } catch (Exception e) {
                log.error(e.getMessage());
                throw new RuntimeException("系统异常");
            }
        }
        return sysMenuMapper.findByType(sysMenu.getType());
    }
}
